package com.hhs.storage.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.hhs.storage.bean.*;
import com.hhs.storage.service.BaseDepartmentService;
import com.hhs.storage.service.BaseLogsService;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 部门规则：只有一个最外层的部门 pid为null
 *         每个人只有一个部门
 * @author hhs
 * @since 2023-01-12
 */
@RestController
@RequestMapping("/depart")
@ApiSupport(order = 3)      //排序
@Api(tags = "部门操作接口")   //
public class BaseDepartmentController {
    @Resource
    private BaseLogsService baseLogsService;
    @Resource
    BaseDepartmentService baseDepartmentService;

    @ApiOperation(value = "得到所有部门负责人",
            notes = "得到所有部门负责人",
            httpMethod = "POST"
    )
    @ApiOperationSupport(order = 1)
    @RequestMapping("allHeaders")
    public ResponseBean<List<BaseUser>> allHeaders() {
        Map<String, Object> map = this.getAllHeaders();
        //排除掉系统管理员
        List<BaseUser> list=(List)map.get("data");
        List<BaseUser> l=list.stream().filter(bean -> !"2".equals(bean.getId())).collect(Collectors.toList());
        return ResponseBean.success(l);
    }
    /**
     * 获取所有部门负责人
     * @return
     */
    @RequestMapping("getAllHeaders")
    public Map<String, Object> getAllHeaders() {
        return baseDepartmentService.getAllHeaders();
    }
    //查询所有部门
    @RequestMapping("getAll")
    public Map getAll() throws IOException {
        List<BaseDepartment> list = baseDepartmentService.getAll();
        list = BaseDepartment.format(list,null);
        return  ResponseInfo.success(list);
    }

    @RequestMapping("edit")
    public Map<String, Object> edit(BaseDepartment baseDepartment) {
        if (StringUtils.isEmpty(baseDepartment.getId())){
            baseLogsService.log("部门管理","新增",null);
        }else{
            baseLogsService.log("部门管理","编辑",null);
        }
        return baseDepartmentService.addOrUpdate(baseDepartment);
//        baseDepartmentService.saveOrUpdate(baseDepartment);
    }

    @DeleteMapping(value = "{id}")
    public Map<String, Object> dele(@PathVariable("id") String id) {
        baseLogsService.log("部门管理","删除",null);
        return baseDepartmentService.dele(id);

    }
    /**
     * @Author: HuangHaiShui
     * @Description:获取用户的所属部门与岗位（负责人或职员）
     * @Date: 18:57 2023/1/12
     * @param userId:
     **/
                @GetMapping(value = "getByUserId")
                public Map<String, Object> findByUserId( String userId) {
                    List<BaseDepartment> list = baseDepartmentService.findByUserId(userId);
                    return ResponseInfo.success(list);
                }
    //获取职员的其他可见部门
    @GetMapping(value = "getSeeByUserId")
    public Map<String, Object> getSeeByUserId( String userId) {
        List<BaseDepartment> list = baseDepartmentService.findSeeByUserId(userId);
        return ResponseInfo.success(list);
    }

    //departId 职员所属部门，seeDepartId 职员其他可见部门，用于首页计划的查看
    @RequestMapping("join")
    public Map<String, Object> join(String userId,String departId,String seeDepartId,Integer type) {
        baseLogsService.log("部门管理","用户分配部门",null);
        return baseDepartmentService.join(userId,departId,seeDepartId,type);
    }

    //获取某个部门的人员，分页，传入id字段作为部门id
    //仅系统管理-部门用户使用该接口
    @RequestMapping("users")
    @ApiOperation(value = "获取某个部门的人员，分页,id传0表示领导",
            notes = "获取某个部门的人员，分页，传入id字段作为部门id,id传0表示领导",
            httpMethod = "POST"
    )
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "id", value = "传入id字段作为部门id,id传0表示领导", required =
                    true, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "page", value = "页号", required =
                    true, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "size", value = "每页大小", required =
                    true, paramType = "query")
    })
    public ResponseBeanPage<BaseUser> users(@ApiIgnore InputParam inputParam) {
        ResponseBeanPage res=ResponseBeanPage.getInstance();
        if("0".equals(StringUtil.zNull(inputParam.getId()))){//领导分组
            Page page = baseDepartmentService.getAllHeaders(inputParam);
            res.setCode(1);
            res.setRows(page.getRecords());
            res.setTotal(page.getTotal());
            return res;
        }
        inputParam.setQueryType(5);
        Map<String, Object> users = baseDepartmentService.getUsers(inputParam);
        res.setCode((Integer)users.get("code"));
        res.setTotal((Long)users.get("total"));
        res.setRows((List<BaseUser>)users.get("rows"));
        return res;
    }
    //获取某个部门的人员，分页，传入id字段作为部门id
    @RequestMapping("getUsers")
    public Map<String, Object> getUsers(InputParam inputParam) {
        return baseDepartmentService.getUsers(inputParam);
    }

    //获取某个部门的人员，分页，传入id字段作为部门id，排除特定人员
    @RequestMapping("getUsersEx")
    public Map<String, Object> getUsersEx(InputParam inputParam) {
        return baseDepartmentService.getUsersEx(inputParam);
    }

    //判断是否为部门负责人
    @RequestMapping("isPrincipal")
    public Map<String, Object> isPrincipal(HttpServletRequest request,InputParam inputParam) throws IOException {
        //若没有传递负责人id,则读取当前请求发起人的id
        if(StringUtils.isEmpty(inputParam.getCurUserId())) {
            String createrId = SysUtil.getLoginUserId(request);
            inputParam.setCurUserId(createrId);
        }
        return baseDepartmentService.isPrincipal(inputParam);
    }

    /**
     * 获取当前登录用户的部门和下级部门信息
     * @return
     */
    @RequestMapping("getDepartDataByLoginUser")
    public Map<String, Object> getDepartDataByLoginUser() {
        return baseDepartmentService.getDepartDataByLoginUser(new InputParam());
    }

    @RequestMapping("test")
    public Map<String, Object> test(HttpServletRequest request) {
//        String userId = SysUtil.getLoginUserId(request);
//         List< BaseUser > userList=baseDepartmentService.getUserDepartAllUser(userId);
        return  ResponseInfo.success(null);
    }

    /**
     * 获取当前登录用户的部门领导信息
     * 2023-04-21修改 还要查上上级部门领导
     * @return
     */
    @RequestMapping("getDepartHeader")
    public Map<String, Object> getDepartHeader() {
        return baseDepartmentService.getDepartHeader();
    }
    /**
     * 获取用户的所属部门与子部门
     * @return
     */
    @RequestMapping("getUserDepartInfo")
    public Map<String, Object> getUserDepartInfo() {
        return baseDepartmentService.getUserDepartInfo();
    }
    /**
     * 获取每个部门有多少员工
     * type:1 包含了用户status 为0 的
     * @return
     */
    @RequestMapping("sumUsers")
    public Map<String, Object> sumUsers(Integer type) {
        return baseDepartmentService.sumUsers(type);
    }

    //查询当前用户首页的可见部门（包含所属部门以及额外配置的所见部门）
    @RequestMapping("indexDepart")
    public Map<String, Object> indexDepart() {
        return baseDepartmentService.indexDepart();
    }

    //计划单元格 查询是否有操作权限
    //负责人可以查看所属部门以及下级部门
    //若下级员工有多个部门，是其他部门的负责人，需要判断部门的级别高低，级别低，负责人才能操作
    @RequestMapping("principalOpera")
    public Map<String, Object> principalLevel(String userId) {
        return baseDepartmentService.principalOpera(userId);
    }

    /**
     * 根据当前用户的部门关系类型获取部门数据
     * @param type leader=查询上级 user=查询下级
     * @return
     */
    @RequestMapping("getDepartByRelateType")
    public Map<String, Object> getDepartByRelateType(@RequestParam String type) {
        return baseDepartmentService.getDepartByRelateType(type);
    }

    /**
     * 根据关系类型获取部门用户数据
     * @param type  leader=查询负责人 user=查询职员
     * @param departIds
     * @return
     */
    @RequestMapping("getDepartUserDataByRelateType")
    public Map<String, Object> getDepartUserDataByRelateType(@RequestParam String type,@RequestParam String departIds) {
        return baseDepartmentService.getDepartUserDataByRelateType(type,departIds);
    }


    /**
     * 获取专属业务部门
     * @return
     */
    @RequestMapping("getBusinessSiteDepart")
    public Map<String, Object> getBusinessSiteDepart() {
        return baseDepartmentService.getBusinessSiteDepart();
    }
}

